"""
用户管理
"""
import logging

from django.urls import reverse
from django.shortcuts import redirect

from oracle.base import baseview
from oracle.models import OUserInfo
from oracle.base.basemodel import Status
from oracle.base.tools import get_random_string
from oracle.forms.user import UserCreateForm, UserUpdateForm, UserPasswordResetForm

logger = logging.getLogger(__name__)


def user_list(request):
    """
    用户列表
    :param request:
    :return:
    """
    data = dict()
    status = "success"
    template = "oracle/user_list.html"

    userinfo_queryset = OUserInfo.objects.all()
    data["user_list"] = list()
    for obj in userinfo_queryset:
        data["user_list"].append({"name": obj.name, "email": obj.email, "key": obj.key})

    baseview.get_context_data(request, logger, data)
    return baseview.render_handler(request, status, template=template, data=data)


def user_add(request):
    """
    创建用户
    :param request:
    :return:
    """
    data = dict()
    status = "success"
    template = None

    if request.method == "GET":
        # 获取csrf
        csrf_token = request.META.get("CSRF_COOKIE")
        return_url = reverse("oracle:user_list")
        form = UserCreateForm()
        data = {
            "csrf_token": csrf_token,
            "status": Status.choices,
            "return_url": return_url,
            "form_key": list(form.fields.keys()),
            "form": form,
            "form_name": "新建用户",
            "form_description": "",

        }
        template = "oracle/change.html"
    elif request.method == "POST":
        # 验证form
        form = UserCreateForm(request.POST)
        # form合法
        if form.is_valid():
            # 获取form返回的实例，key需要单独生成，所以目前先不进行保存
            obj = form.save(commit=False)
            # TODO 性能问题
            # 确保获取的key唯一
            while True:
                key = get_random_string(24)
                if not OUserInfo.objects.filter(key=key, status=0).exists():
                    break
            # 定义唯一key并进行保存
            obj.key = key
            obj.save()

            def method(r, t, d):
                return redirect(reverse("oracle:user_list"))
        # 校验没有通过
        else:
            return_url = reverse("oracle:user_list")
            # 设置错误信息，如果外部渲染传给前端
            data = {
                "error": form.errors,
                "return_url": return_url,
                "form": form,
                "form_name": "新建用户",
                "form_description": "",
            }
            status = "model_valid_check_failed"
            template = "oracle/change.html"
    # 非get或者post方法访问进行友好报错处理
    else:
        status = "method_not_allow"
    baseview.get_context_data(request, logger, data)
    return baseview.render_handler(request, status, template=template, data=data)


def user_edit(request, key):
    """
    修改用户
    :param request:
    :param key: 要修改的用户索引
    :return:
    """
    data = dict()
    status = "success"
    template = None

    # 获取要修改的实例信息
    obj = OUserInfo.objects.filter(key=key, status=0).first()
    if request.method == "GET":
        # 如果有实例则返回修改页面信息
        if obj:
            return_url = reverse("oracle:user_list")
            # 获取csrf
            csrf_token = request.META.get("CSRF_COOKIE")
            form = UserUpdateForm(instance=obj)
            data = {
                "csrf_token": csrf_token,
                "status": Status.choices,
                "user": form.initial,
                "return_url": return_url,
                "form": form,
                "form_name": "修改用户",
                "form_description": "",
            }
            template = "oracle/change.html"
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    elif request.method == "POST":
        if obj:
            # 验证form
            form = UserUpdateForm(instance=obj, data=request.POST)
            # form合法
            if form.is_valid():
                # 获取form返回的实例，key需要单独生成，所以目前先不进行保存
                form.save()

                def method(r, t, d):
                    return redirect(reverse("oracle:user_list"))
            # 校验没有通过
            else:
                return_url = reverse("oracle:user_list")
                # 设置错误信息，如果外部渲染传给前端
                data = {
                    "error": form.errors,
                    "return_url": return_url,
                    "form": form,
                    "form_name": "修改用户",
                    "form_description": "",
                }
                status = "model_valid_check_failed"
                template = "oracle/change.html"
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    # 非get或者post方法访问进行友好报错处理
    else:
        status = "method_not_allow"
    baseview.get_context_data(request, logger, data)
    return baseview.render_handler(request, status, template=template, data=data)


def user_password_reset(request, key):
    """
    修改用户密码
    :param request:
    :param key: 要修改的用户索引
    :return:
    """
    data = dict()
    status = "success"
    template = None
    method = None

    # 获取要修改的实例信息
    obj = OUserInfo.objects.filter(key=key).first()
    if request.method == "GET":
        # 如果有实例则返回修改页面信息
        if obj:
            return_url = reverse("oracle:user_list")
            # 获取csrf
            csrf_token = request.META.get("CSRF_COOKIE")
            form = UserPasswordResetForm()
            data = {
                "csrf_token": csrf_token,
                "status": Status.choices,
                "user": list(form.fields.keys()),
                "return_url": return_url,
                "form": form,
                "form_name": "修改用户密码",
                "form_description": "",
            }
            template = "oracle/change.html"
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    elif request.method == "POST":
        if obj:
            # 验证form
            form = UserPasswordResetForm(instance=obj, data=request.POST)
            # form合法
            if form.is_valid():
                # 获取form返回的实例，key需要单独生成，所以目前先不进行保存
                form.save()

                def method(r, t, d):
                    return redirect(reverse("oracle:user_list"))
            # 校验没有通过
            else:
                return_url = reverse("oracle:user_list")
                # 设置错误信息，如果外部渲染传给前端
                data = {
                    "error": form.errors,
                    "return_url": return_url,
                    "form": form,
                    "form_name": "修改用户密码",
                    "form_description": "",
                }
                status = "model_valid_check_failed"
                template = "oracle/change.html"
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    # 非get或者post方法访问进行友好报错处理
    else:
        status = "method_not_allow"
    baseview.get_context_data(request, logger, data)
    return baseview.render_handler(request, status, template=template, data=data)


def user_del(request, key):
    """
    删除用户
    :param request:
    :param key: 要删除的用户索引
    :return:
    """
    data = dict()
    status = "success"
    template = None
    method = None

    # 获取要删除的实例信息
    obj = OUserInfo.objects.filter(key=key).first()
    if request.method == "GET":
        # 如果有实例则返回修改页面信息
        if obj:
            # 获取csrf
            csrf_token = request.META.get("CSRF_COOKIE")
            return_url = reverse("oracle:user_list")
            data = {
                "csrf_token": csrf_token,
                "object": obj.name,
                "return_url": return_url,
                "form_name": "删除用户",
                "form_description": "",
            }

            template = "oracle/delete_confirm.html"
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    elif request.method == "POST":
        if obj:
            # 实例直接进行删除
            obj.delete()

            def method(r, t, d):
                return redirect(reverse("oracle:user_list"))
        # 没有实例则返回人性化错误信息
        else:
            # 设置错误信息，如果外部渲染传给前端
            status = "model_object_not_exist"
    # 非get或者post方法访问进行友好报错处理
    else:
        status = "method_not_allow"
    baseview.get_context_data(request, logger, data)
    return baseview.render_handler(request, status, template=template, data=data)
